package com.hrms.service;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateUtils;

import com.hrms.core.Constants;
import com.hrms.core.EmailMsg;
import com.hrms.core.TemplateManager.Templates;
import com.hrms.core.Utils;
import com.hrms.domain.BusinessObjectImpl;
import com.hrms.domain.Employee;
import com.hrms.domain.LastUserAction;

/**
 * Servlet implementation class SendMailService
 *
 * @web.servlet
 *   name="DailyReport"
 *
 * @web.servlet-mapping
 *   url-pattern="/cron/DailyReport.do"
 */
public class DailyReport extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger log = Logger.getLogger(DailyReport.class.getName());
	
	private static Date today = null;
	private static Date dayLimit = null;
	private static Map<String, Employee> employeeMap = null;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DailyReport() {
        super();        
    }

    
    private void initialize() {
		today = Utils.getTodayDate();		
		log.info("today is "+today.toString());
		
		dayLimit = DateUtils.addDays(today, -5);
		log.info("dayLimit is "+dayLimit.toString());
		
		employeeMap = Employee.fetchMappedEmploee();
		log.info("Loading Team Map of "+employeeMap.size());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	log.info("STARTED- Executing Cron Jobs");
	
	log.info("Started initialize...");
		initialize();
	log.info("Ended initialize...");
	
		sendRemindersToUpdate();
		
	log.info("FINISHED- Executing Cron Jobs");
	}


	private void sendRemindersToUpdate() {
		try{
			
			for(String user : employeeMap.keySet()){
				
				LastUserAction tmp = BusinessObjectImpl.selectAsSingleResult(LastUserAction.class, "where userId==:p0 ", new Object[]{ user });
				Boolean shouldSendAlert = (tmp != null) ? tmp.getDate().before(dayLimit) : Boolean.TRUE;

				if(shouldSendAlert){
									
				Employee emp = employeeMap.get(user);
				
				// not sending to team email address, coz It's not real
				if(StringUtils.isNotBlank( emp.getInitials() )  &&  emp.getInitials().length() != Constants.TEAM_INTIALS_LIMIT){
				
						Map<String, Object> params = new HashMap<String, Object>();
						params.put("to", emp.getName());
						params.put("appId", Constants.APP_ID);

						EmailMsg email = new EmailMsg();
						email.getRecipients().add(user);
						email.setSubject("Team Dashboard:- Reminder");
						email.setTemplate(Templates.reminder);
						email.setParams(params);
						email.send();
					}
				
				}
			}
			
		}catch (Exception e) {
			new EmailMsg("charmsstyler@gmail.com", "Failed to run DailyReport.do", e.toString()).send();
			log.log(Level.SEVERE, "Failed to alertSupervisorOnTeamPendindLeave", e);
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doGet(req, resp);
	}

	
}
